package com.dqp.cslggroup.JWC;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;

import com.dqp.cslggroup.ConnectSever.SeverIP;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.DialogView;
import com.dqp.cslggroup.UI.MyApplication;
import com.dqp.cslggroup.Util.NetCheckUtil;
import com.dqp.cslggroup.Util.SharedPreferencesUtil;
import com.dqp.cslggroup.Util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.util.List;
import java.util.Objects;


public class JW_tip extends BaseActivity {
    private String use_url;
    private ListView listView;
    private List tip_text, tip_url;
    private boolean select = true;
    private ViewStub viewstub_loading;
    private ViewStub viewstub_null;
    private String Authorization = SharedPreferencesUtil.getStringSp(MyApplication.getContext(), "Authorization", "");

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.jw_tip);
        EventBus.getDefault().register(this);
        initCmp();
        selectUrl();
        if (NetCheckUtil.checkNet(JW_tip.this))
            getTip();
        else {
            viewstub_loading.setVisibility(View.GONE);
            viewstub_null.setVisibility(View.VISIBLE);
            ToastUtil.showToast("请连接网络！");
        }

    }

    private void initCmp() {
        Toolbar toolbar = findViewById(R.id.include_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        TextView imageButton = findViewById(R.id.seting);
        imageButton.setVisibility(View.VISIBLE);
        listView = findViewById(R.id.tip_list);
        viewstub_loading = findViewById(R.id.viewstub_loading);
        viewstub_null = findViewById(R.id.viewstub_null_date);
        imageButton.setOnClickListener(view -> DialogView.selectNet(this, select, (radioGroup, dialog) -> radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if (group.getCheckedRadioButtonId() == R.id.checktv_wai) {
                select = true;
                listView.setAdapter(null);
                selectUrl();
                viewstub_loading.setVisibility(View.VISIBLE);
                getTip();
            } else if (group.getCheckedRadioButtonId() == R.id.checktv_nei) {
                select = false;
                listView.setAdapter(null);
                selectUrl();
                viewstub_loading.setVisibility(View.VISIBLE);
                getTip();
            }
            dialog.dismiss();
        })));
    }

    private void selectUrl() {
        if (!select) {
            use_url = "http://jwc.cslg.cn";
        } else {
            SharedPreferences sp;
            SharedPreferences.Editor editor;
            sp = PreferenceManager.getDefaultSharedPreferences(this);
            editor = sp.edit();
            String ip = sp.getString("ip", SeverIP.getDefvalueUrl());
            use_url = ip + ":8886";
            editor.apply();
        }
    }

    @SuppressLint("HandlerLeak")
    public void getTip() {
        viewstub_loading.setVisibility(View.VISIBLE);
        new Thread(() -> {
            Connection.Response response;
            try {

                response = Jsoup.connect(use_url + "/jwxx.htm")
                        .ignoreContentType(true)
                        .userAgent("Mozilla")
                        .header("Authorization", Authorization)
                        .method(Connection.Method.GET)
                        .timeout(5000)
                        .execute();
                Document document = Jsoup.parse(response.body());
                tip_text = document.select("a[class=fl]").eachText();
                tip_url = document.select("a[class=fl]").eachAttr("href");
                int text_length = tip_url.size();
                EventBus.getDefault().post(new MessageEvent("JW_tip", 1, text_length));
            } catch (IOException e) {
                e.printStackTrace();
                EventBus.getDefault().post(new MessageEvent("JW_tip", 2, null));
            }
        }).start();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            super.onDestroy();
            this.finish();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("JW_tip")) {
            if (event.getWhat() == 1) {
                String[] text = new String[20];
                for (int i = 0; i < event.getZhou() && i < 20; i++) {
                    text[i] = tip_text.get(i).toString();
                }
                ArrayAdapter arrayAdapter = new ArrayAdapter<>(JW_tip.this, android.R.layout.simple_list_item_1, text);
                listView.setAdapter(arrayAdapter);
                listView.setOnItemClickListener((adapterView, view, i, l) -> {
                    String url = tip_url.get(i).toString();
                    String urls = use_url + "/" + url;
                    Intent intent = new Intent(JW_tip.this, Tip_main.class);
                    intent.putExtra("url", urls);
                    startActivity(intent);
                });
                viewstub_loading.setVisibility(View.GONE);
            }
            if (event.getWhat() == 2) {
                viewstub_loading.setVisibility(View.GONE);
                viewstub_null.setVisibility(View.VISIBLE);
                ToastUtil.showToast("数据请求失败！");
            }
        }
    }
}
